package com.electric.qrapp.utils.function

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import java.io.*
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketException
import java.util.*

/**
 *@author created by WA03675
 *@date  2022-04-02 16:35
 *@des 网络工具类
 */


object NetUtils {


    //没有网络连接
    const val NETWORN_NONE = 0

    //wifi连接
    const val NETWORN_WIFI = 1

    //手机网络数据连接类型
    const val NETWORN_2G = 2
    const val NETWORN_3G = 3
    const val NETWORN_4G = 4
    const val NETWORN_MOBILE = 5

    /**
     * 判断当前网络是否可用
     *
     * @param context
     * @return
     */
    fun isNetworkConnected(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val ni = connectivityManager.activeNetworkInfo
        return ni != null && ni.isConnectedOrConnecting
    }

    /**
     * 获取当前网络连接类型
     *
     * @param context
     * @return
     */
    fun getNetworkState(context: Context): Int {
        //获取系统的网络服务
        val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager ?: return NETWORN_NONE

        //如果当前没有网络

        //获取当前网络类型，如果为空，返回无网络
        val activeNetInfo = connManager.activeNetworkInfo
        if (activeNetInfo == null || !activeNetInfo.isAvailable) {
            return NETWORN_NONE
        }

        // 判断是不是连接的是不是wifi
        val wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        if (null != wifiInfo) {
            val state = wifiInfo.state
            if (null != state) if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                return NETWORN_WIFI
            }
        }

        // 如果不是wifi，则判断当前连接的是运营商的哪种网络2g、3g、4g等
        val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
        if (null != networkInfo) {
            val state = networkInfo.state
            val strSubTypeName = networkInfo.subtypeName
            if (null != state) if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                return when (activeNetInfo.subtype) {
                    TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> NETWORN_2G
                    TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> NETWORN_3G
                    TelephonyManager.NETWORK_TYPE_LTE -> NETWORN_4G
                    else ->                             //中国移动 联通 电信 三种3G制式
                        if (strSubTypeName.equals("TD-SCDMA", ignoreCase = true) || strSubTypeName
                                .equals("WCDMA", ignoreCase = true) || strSubTypeName.equals("CDMA2000", ignoreCase = true)
                        ) {
                            NETWORN_3G
                        } else {
                            NETWORN_MOBILE
                        }
                }
            }
        }
        return NETWORN_NONE
    }

    /**
     * 判断当前是否为gprs网络
     *
     * @author gut
     */
    fun isGPRS(context: Context): Boolean {
        val connectivityManager = context
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetInfo = connectivityManager.activeNetworkInfo
        return (activeNetInfo != null
                && activeNetInfo.type == ConnectivityManager.TYPE_MOBILE)
    }

    /**
     * 获取网络类型
     *
     * @return
     */
    fun getNetWorkType(context: Context): String {
        val connectMgr = context
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val info = connectMgr.activeNetworkInfo
        var type = ""
        if (info != null) {
            when (info.type) {
                ConnectivityManager.TYPE_WIFI -> type = "WIFI"
                ConnectivityManager.TYPE_MOBILE -> when (info.subtype) {
                    TelephonyManager.NETWORK_TYPE_LTE, TelephonyManager.NETWORK_TYPE_HSPAP, TelephonyManager.NETWORK_TYPE_EHRPD -> type = "4G"
                    TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_EVDO_B -> type =
                        "3G"
                    TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE -> type = "2G"
                }
            }
        }
        return type
    }

    /**
     * 判断是否有网络
     *
     * @param error
     * @return
     */
    fun isNoNetwork(error: String): Boolean {
        if (TextUtils.isEmpty(error)) {
            return false
        }
        return error.contains("UnknownHostException") || error.contains("TimeoutException") || error
            .contains("ConnectException")
    }

    /**
     * 获取ssid信息
     *
     * @param context
     * @return
     */
    fun getSSID(context: Context): String {
        var result = ""
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (connectivityManager != null && connectivityManager.activeNetworkInfo != null) {
            if (connectivityManager.activeNetworkInfo!!.type == ConnectivityManager.TYPE_WIFI) {
                val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
                val wifiInfo = wifiManager.connectionInfo
                if (wifiInfo != null) {
                    result = wifiInfo.ssid
                }
            }
        }
        return result
    }




    fun readFile(filePath: String?): String {
        val result = StringBuffer()
        var line: String? = null
        var buffReader: BufferedReader? = null
        try {
            buffReader = BufferedReader(
                InputStreamReader(
                    FileInputStream(filePath),
                    "GBK"
                )
            )
            while (buffReader.readLine().also { line = it } != null) {
                result.append(line).append("\n")
            }
            buffReader.close()
        } catch (var8: UnsupportedEncodingException) {
            var8.printStackTrace()
        } catch (var9: FileNotFoundException) {
            var9.printStackTrace()
        } catch (var10: IOException) {
            var10.printStackTrace()
        } finally {
            buffReader = null
        }

        return result.toString()
    }

    /**
     * 获取ip地址
     *
     * @param connectType
     * @return
     */
    fun getLocalIP(connectType: Int): String? {

        var result: String? = ""
        if (connectType == 1) {
            result = getSystemProperties("dhcp.eth0.ipaddress")
        } else {
            try {
                val ex: Enumeration<*> = NetworkInterface.getNetworkInterfaces()
                while (ex.hasMoreElements()) {
                    val intf = ex.nextElement() as NetworkInterface
                    val enumIPAddr: Enumeration<*> = intf.inetAddresses
                    while (enumIPAddr.hasMoreElements()) {
                        val inetAddress = enumIPAddr.nextElement() as InetAddress
                        if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                            result = inetAddress.getHostAddress().toString()
                            break
                        }
                    }
                    if (result != null && result.length > 0) {
                        break
                    }
                }
            } catch (var6: SocketException) {
                result = ""
                System.err.print("error")
            }
        }
        return result
    }

    fun getSystemProperties(key: String): String? {
        var str: String? = null
        try {
            val e = Class.forName("android.os.SystemProperties")
            val get = e.getMethod("get", *arrayOf<Class<*>>(String::class.java))
            str = get.invoke(e, *arrayOf<Any>(key)) as String
        } catch (var4: Exception) {
            var4.printStackTrace()
        }
        return str
    }


}